/**
 * 研讨内页
 */
var localStorageManagers = require('script/localStorageManagers.js');
var downloadUtils = require('scripts/Core/DownLoadUtil.js');
//mui初始化
mui.init({
	swipeBack: false
});
FastClick.attach(document.body);
//plus初始化
mui.plusReady(function() {
	plusReady();
});
//plusReady
function plusReady() {
	//延迟加载
	mui('.elseinfo').imageLazyload({
		placeholder: '../../images/user_guest.png'
	});
	//加载研讨信息
	loadDiscussinfo();
	//点击文件
	mui('#disfiles').on('tap', 'span', openEmptyPage);
	//点击视频
	mui('#videolist').on('tap', 'span', openVideo);
	//下载视频
	mui('header').on('tap', '#downloadvideo', downLoadVideo);
	//点击回答按钮事件
	mui('.questions').on('tap', '.question .reply-div', openAnswerques);
	//取消提问
	mui('.putques-div').on('tap', '.cancelques', cancelQues);
	//保存提问
	mui('.putques-div').on('tap', '.submitques', savePutques);
	//新增提问按钮
	mui('.mui-content').on('tap', '#addquesdiv', openAnswerques);
	//设置屏幕高度
	autoWidthHeight();
	document.addEventListener("pause", function () {
	   pauseVideo();
      //console.log("应用从前台切换到后台");
    }, false);
    document.addEventListener("resume", function () {
       //playVideo();
      // console.log("应用从后台切换到前台");
    }, false);
};
//设置高度自适应
function autoWidthHeight() {
	var clienth = document.documentElement.clientHeight;
	var titleh = document.getElementsByClassName('mui-bar-nav')[0].offsetHeight;
	var videoh = document.getElementsByClassName('mui-content-view')[0].offsetHeight;
	var contentsdiv = document.getElementsByClassName('mui-control-content');
	var temph = clienth - titleh - videoh;
	for (var i = 0; i < contentsdiv.length; i++) {
		contentsdiv[i].style.height = temph - 100 + 'px';
	}
	//设置按钮位置
	//document.getElementById('addquesdiv').style.marginTop=temph - 192 + 'px';
};
//加载研讨信息
function loadDiscussinfo() {
	document.getElementById('videolist').innerHTML = ' ';
	document.getElementById('questions').innerHTML = ' ';
	document.getElementById('disfiles').innerHTML = ' ';
	ajaxLoadDiscussinfo();
}
//ajax加载研讨信息
function ajaxLoadDiscussinfo() {
	var self = plus.webview.currentWebview();
	var discussid = self.discussid;
	var discussname = self.discussname;
	if (discussname.length > 15) discussname = discussname.substring(0, 15) + '..';
	document.getElementById('discusstitle').innerHTML = discussname;
	document.getElementById('discusstitle1').innerHTML = discussname;
	document.getElementById('fDiscussid').value = discussid;
	document.getElementById('fDiscussname').value = self.discussname;
	var url = serverAjax + "mobile/studycenter/getDiscussById.do";
	mui.ajax(url, {
		data: {
			discussid: discussid
		},
		type: 'post',
		dataType: 'json',
		timeout: 10000,
		success: function(data) {
			//基本信息
			buildDiscussBasic(data.discussInfo);
			//附件信息
			buildAttachDiv(data.attachList);
			//问题列表
			buildQuestionDiv(data.quesList);
			//mui('.elseinfo').imageLazyload({
			//	placeholder: '../../images/user_guest.png'
			//});
		},
		error: function(e1, e2, e3) {
			ajaxErrorTip();
			console.log(e1);
		}
	});
}
//构建研讨基本信息
function buildDiscussBasic(discuss) {
	//document.getElementById('discusstitle').innerText = discuss.title;
	//document.getElementById('discusstitle1').innerText = discuss.title;
	document.getElementById('discusscreate').innerHTML = discuss.createName + "(老师)<span class='createtime'>" + discuss.createtime + "</span>";
	document.getElementById('discussyaoqiu').innerText = discuss.content;
}
//构建附件列表
function buildAttachDiv(attachList) {
	for (var i = 0; i < attachList.length; i++) {
		var attach = attachList[i];
		var attachname = attach.name;
		if (attachname.length > 9) attachname = attachname.substring(0, 7) + '..';
		if (attach.type == 0) { //视频
			var videostr = '<span class="video-span"  attachid="' + attach.id + '" name="' + attach.name + '" path="' + attach.path + '">' + attachname + '</span>';
			document.getElementById('videolist').innerHTML = document.getElementById('videolist').innerHTML + videostr;
			document.getElementById('downloadvideo').style.display='block';
		} else if (attach.type == 1) { //文件
			var filestr = '<span class="discussfile" attachid="' + attach.id + '" name="' + attach.name + '" path="' + attach.path + '">' + attachname + '</span>';
			document.getElementById('disfiles').innerHTML = document.getElementById('disfiles').innerHTML + filestr;
		}
	}
}
//构建问题列表
function buildQuestionDiv(quesList) {
	for (var i = 0; i < quesList.length; i++) {
		var question = quesList[i];
		var parentid = question.parentId;
		if (parentid == 0) {
			var questionsdiv = document.getElementById('questions');
			var imgsrc = "../../images/user_guest.png";
			if (question.userpath != null && question.userpath.length > 0) imgsrc = question.userpath;

			var questionstr = '<div class="question">' + '<div class="ques-content">' + '<div class="elseinfo"><span class="userimg"><img src="' + imgsrc + '"></span>' + '<p class="p1">' + question.creator + '</p>' + '<p class="p2"><span class="c1">机械设计(1)班</span><span class="c2">' + question.createTime + '</span></p>' + '</div>' + '<div class="content-value">' + question.content + '</div>' + '<div class="reply-div" questionid="' + question.id + '"><img src="../../images/reply.png"></div>' + '</div>' + '<div class="ques-answers" id="parentquestionid_' + question.id + '">' + '</div>' + '</div>';
			questionsdiv.innerHTML = questionsdiv.innerHTML + questionstr;
		} else {
			var parentquestioniddiv = document.getElementById('parentquestionid_' + question.parentId);
			//第一层提问
			if (parentquestioniddiv != null) {
				var questionstr = '<div class="answer" id="erjiquestionid_' + question.id + '">' + '<div class="answeruser"><span>' + question.creator + '</span><span class="date">' + question.createTime + '</span></div>' + '<div class="answer-content"><span class="hfc">' + question.content + '</span></div>' + '</div>';
				parentquestioniddiv.innerHTML = parentquestioniddiv.innerHTML + questionstr;
			} else {
				//第二层
				var parentquestioniddiv2 = document.getElementById('erjiquestionid_' + question.parentId);
				if (parentquestioniddiv2 != null) {
					//var questionstr = '<div class="answer" id="erjiquestionid_' + question.id + '">' + '<div class="answeruser"><span>' + question.creator + '</span><span class="date">' + question.createTime + '</span></div>' + '<div class="answer-content"><span class="hfc">' + question.content + '</span></div>' + '</div>';
					var questionstr = '<div class="answeruser"><span>' + question.creator + '</span><span class="date">' + question.createTime + '</span></div>' + '<div class="answer-content"><span class="hfc">' + question.content + '</span></div>';
					//parentquestioniddiv2.parent.innerHTML = parentquestioniddiv2.parent.innerHTML + questionstr;
					var newdiv = document.createElement("div");
					newdiv.className = 'answer';
					newdiv.id = 'erjiquestionid_' + question.id + '';
					newdiv.innerHTML = questionstr;
					insertAfter(newdiv, parentquestioniddiv2);
					//parentquestioniddiv2.parentNode.innerHTML=parentquestioniddiv2.parentNode.innerHTML+questionstr;
				}
			}
		}
	}
}
//后面插入
function insertAfter(newEl, targetEl) {
	var parentEl = targetEl.parentNode;

	if (parentEl.lastChild == targetEl) {
		parentEl.appendChild(newEl);
	} else {
		parentEl.insertBefore(newEl, targetEl.nextSibling);
	}
}
//打开不能查看页面
function openEmptyPage() {
	//点击样式
	var ddivs=document.getElementsByClassName('discussfile');
	for(var i=0;i<ddivs.length;i++){
		ddivs[i].className='discussfile';
	}
	this.className='discussfile cur';
	
	var discussid = document.getElementById('fDiscussid').value;
	var discussname = document.getElementById('fDiscussname').value;
	var attachid = this.getAttribute('attachid');
	var attachname = this.getAttribute('name');
	var path = this.getAttribute('path');
	mui.openWindow({
		url: 'viewEmptyPage.html',
		id: 'selfcenter/classdiscuss/viewEmptyPage',
		extras: {
			discussid: discussid,
			discussname: discussname,
			attachid: attachid,
			attachname: attachname,
			path: path
		}
	});
}
//打开视频
function openVideo() {
	//点击样式
	var vdivs=document.getElementsByClassName('video-span');
	for(var i=0;i<vdivs.length;i++){
		vdivs[i].className='video-span';
	}
	this.className='video-span cur';
	
	var path = this.getAttribute('path');
	var attachid = this.getAttribute('attachid');
	var attachtitle = this.getAttribute('name');
	document.getElementById('fVideoPath').value = path;
	document.getElementById('fAttachid').value = attachid;
	document.getElementById('fAttachtitle').value = attachtitle;
	//获得本地缓存路径，没有缓存则使用网络路径
	var localpath = downloadUtils.getLocalAbsoluteUrl(path);
	if (localpath != null) path = localpath;
	console.log(path);
	//var videostr = '<video id="v" controls="controls" style="width:100%;height:99%;background-color:#2E2E2E"  autoplay="autoplay" poster="../images/video_bg.jpg" src="' + path + '">' + '<object  type="application/x-shockwave-flash" data="myvideo.swf"><param name="movie" value="myvideo.swf" />' + '<param name="flashvars" value="autostart=true&amp;file=myvideo.swf" /></object>' + '当前手机不支持 video直接播放，点击这里下载视频： <a href="myvideo.webm">下载视频</a></video>';
	//document.getElementById('viewres').innerHTML = videostr;
	var videostr = '<video id="myVideo" controls="controls" style="width:100%;height:99%;background-color:black"  autoplay="autoplay" poster="../../images/video_bg.jpg" src="' + path + '">' + '<object  type="application/x-shockwave-flash" data="myvideo.swf"><param name="movie" value="myvideo.swf" />' + '<param name="flashvars" value="autostart=true&amp;file=myvideo.swf" /></object>' + '当前手机不支持 video直接播放，点击这里下载视频： <a href="myvideo.webm">下载视频</a></video>';
	document.getElementById('viewres').innerHTML = videostr;
	document.getElementById('myVideo').play();
	if(path.endWith('.mp3')||path.endWith('.mp4')){
	   mui.toast('视频正在加载');	
	}else{
	   mui.toast('请在电脑上查看本资源');	
	}
	
}
//下载视频
function downLoadVideo() {
	var attachid = document.getElementById('fAttachid').value;
	if (attachid <= 0) {
		mui.toast("请选择资源");
		return;
	}
	var discussid = document.getElementById('fDiscussid').value;
	var discussname = document.getElementById('fDiscussname').value;
	var attachtitle = document.getElementById('fAttachtitle').value;
	var path = document.getElementById('fVideoPath').value;
	var key = buildResKey(2, discussid, attachid);
	var res = {
		title: attachtitle,
		key: key,
		path: path,
		resCatName: '视频',
		courseName: discussname,
		catalogName: discussname,
		resSize: '1'
	};
	var issave = localStorageManagers.pushDownresourceSessionItem(res);
	//下载在课程页面进行
	if (issave) {
		var parentWebView = plus.webview.getWebviewById("synccourse/courseindex.html");
		parentWebView.evalJS("downloadResource('" + path + "')");
		mui.toast("开始下载");
	} else {
		mui.toast("已下载");
	}
}
//打开回复问题框
function openAnswerques() {
	var questionid = this.getAttribute('questionid');
	document.getElementById('fParentid').value = questionid;
	document.getElementById('questextarea').value = '';
	document.getElementById('putques-div').style.display = 'block';
};
//取消问题回复框
function cancelQues() {
	document.getElementById('putques-div').style.display = 'none';
}
//保存评论回复
function savePutques() {
	var userid = localStorageManagers.getUseridSession();
	var discussid = document.getElementById('fDiscussid').value;
	var parentid = document.getElementById('fParentid').value;
	var quesContent = document.getElementById('questextarea').value;
	if (quesContent.length == 0) {
		mui.toast("请填写问题内容");
		return;
	}
	if (quesContent.length > 200) {
		mui.toast("最多不超过200字！");
		return;
	}
	var data = {
		userid: userid,
		discussid: discussid,
		parentid: parentid,
		quescontent: quesContent
	}
	ajaxSubmitQuestion(data);
}
//ajax保存问题
function ajaxSubmitQuestion(data) {
	mui.ajax(serverAjax + '/mobile/studycenter/saveDiscussComment.do', {
		type: 'post',
		dataType: 'json',
		data: data,
		timeout: 10000,
		success: function(result) {
			if (result == 1) {
				mui.toast('保存成功');
				document.getElementById('putques-div').style.display = 'none';
				document.getElementById('questions').innerHTML = ' ';
				var self = plus.webview.currentWebview();
				var discussid = self.discussid;
				var url = serverAjax + "mobile/studycenter/getDiscussById.do";
				mui.ajax(url, {
					data: {
						discussid: discussid
					},
					type: 'post',
					dataType: 'json',
					timeout: 10000,
					success: function(data) {
						//问题列表
						buildQuestionDiv(data.quesList);
					},
					error: function(e1, e2, e3) {
						ajaxErrorTip();
						console.log(e1);
					}
				});
			} else {
				mui.toast('保存失败');
			}
		},
		error: function(xhr, type, errorThrown) {
			ajaxErrorTip();
			console.log(xhr);
		}
	});
};

//视频暂停
function pauseVideo(){
	var video=document.getElementById('myVideo');
	if(video!=null){
		document.getElementById("myVideo").pause();
	}
};
//视频开始
function playVideo(){
	var video=document.getElementById('myVideo');
	if(video!=null){
		document.getElementById("myVideo").play();
	}
};